//koa2洋葱模型实现原理
class TaskList {
  constructor () {
    this.list = [];
  }

  use (fn) {
    fn && this.list.push(fn);
  }

  start () {
    const self = this;
    let idx = -1;
    const exec = function () {
      idx++;
      const fn = self.list[idx];
      if (!fn) {
        return Promise.resolve();
      }
      // return Promise.resolve(fn(exec));
      return fn(exec); //TODO 这块不确定使用Promise.resolve的好处
    };
    exec();
  }
}

const test1 = function () {
  return new Promise(resolve => {
    setTimeout(function () {
      console.log('fn1');
      resolve();
    }, 2000);
  });
};

const taskList = new TaskList();

taskList.use(async next => {
  console.log(1);
  await next();
  console.log(2);
});
taskList.use(async next => {
  console.log(3);
  await test1();
  await next();
  console.log(4);
});
taskList.use(async next => {
  console.log(5);
  await next();
  // next();
  console.log(6);
});
taskList.use(async next => {
  console.log(7);
  next();
});

// taskList.use(next => {
//   console.log(8);
// });
taskList.start();

// 输出: 1、3、fn1、5、7、6、4、2
